package WEB.Servlet.Actions;

import DB.dao.PersonDao;
import DB.dto.DoctorDto;
import DB.dto.NurseDto;
import DB.dto.PatientDto;
import DB.dto.PersonDto;
import DB.exceptions.PersonDaoException;
import DB.jdbc.PersonDaoImpl;
import personal.Doctor;
import personal.Nurse;
import personal.Patient;
import personal.Person;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * User: Vanil
 * Date: 06.12.2010
 * Time: 4:51:10
 */
public class LoginAction extends ShowAction {
    @Override
    public String perform(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        PersonDao dao = new PersonDaoImpl();
        PersonDto[] personDtoArr = new PersonDto[1];
        try {
            personDtoArr = dao.findWhereLoginEquals(username);
        } catch (PersonDaoException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.

        }
        if(personDtoArr.length>0)
        {
            PersonDto personDto = personDtoArr[0];
            if(personDto.getPassword().equals(password))
            {
                Person contactUser=null;
                if(personDto instanceof DoctorDto)
                {
                    contactUser = new Doctor((DoctorDto)personDto);
                }
                else
                    if(personDto instanceof NurseDto)
                    {
                        contactUser = new Nurse((NurseDto)personDto);
                    }
                    else
                        if(personDto instanceof PatientDto)
                        {
                             contactUser = new Patient((PatientDto)personDto);
                        }
                request.getSession().setAttribute("sessionUser",(Person) contactUser);
                response.sendRedirect("show.do?id="+contactUser.getIdPerson());
                return null;
            }
        }
        else
             request.getSession().setAttribute("errorMessage","Invalid username/password.");
        return "/error.jsp";
    }
}
